<template>
	<view v-if="show" class="hb-notice-bar" :class="[!scrollable && !wrapable ? 'hb-notice-bar--wrapable':'' ]" :style="{ backgroundColor: backgroundColor,color:color }"
	 @tap="onClick">
		<text v-if="leftIcon" class="hb-icon_notice hb-notice-bar__left-icon"></text>
		<slot v-else name="left-icon" />
		<view :id="elIdBox" class="hb-notice-bar__wrap">
			<view class="hb-notice-bar__content" :id="elId" ref="animationEle" :class="[!scrollable && wrapable?'hb-ellipsis':'',scrollable?'hb-notice-bar-text--scrollable':'']"
			 :style="{'animationDuration': animationDuration, '-webkit-animationDuration': animationDuration ,animationPlayState: webviewHide?'paused':animationPlayState,'-webkit-animationPlayState':webviewHide?'paused':animationPlayState, animationDelay: animationDelay, '-webkit-animationDelay':animationDelay}">
				{{ text }}
			</view>
		</view>
		<text v-if="mode==='closeable'" class="hb-notice-bar__right-icon hb-icon_close" @tap="close"></text>
		<text v-else-if="mode==='link'" class="hb-notice-bar__right-icon hb-icon_arrow-right" @click="clickMore"></text>
		<slot v-else name="right-icon" />
	</view>

</template>

<script>
	// #ifdef APP-NVUE
	const dom = weex.requireModule('dom');
	const animation = weex.requireModule('animation');
	// #endif

	/**
	 * NoticeBar 自定义导航栏
	 * @description 通告栏组件
	 * 
	 * @property {Number} speed 文字滚动的速度，默认100px/秒
	 * @property {String} text 显示文字
	 * @property {String} backgroundColor 背景颜色
	 * @property {String} color 文字颜色
	 * @property {Boolean} wrapable = [true|false] 是否单行
	 * @property {Boolean} scrollable = [true|false] 是否滚动，为true时，NoticeBar为单行
	 * @property {Boolean} leftIcon = [true|false] 是否显示左侧喇叭图标
	 * @event {Function} click 点击 NoticeBar 触发事件
	 * @event {Function} close 关闭 NoticeBar 触发事件
	 * @event {Function} getmore 点击”查看更多“时触发事件
	 */

	export default {
		name: 'HbNoticeBar',
		props: {
			text: {
				type: String,
				default: ''
			},
			backgroundColor: {
				type: String,
				default: '#fffbe8'
			},
			speed: {
				// 默认1s滚动50px
				type: Number,
				default: 50
			},
			color: {
				type: String,
				default: '#de8c17'
			},
			//是否单行
			wrapable: Boolean,
			scrollable: {
				// 是否滚动，添加后控制单行效果取消
				type: [Boolean, String],
				default: false
			},
			leftIcon: {
				// 是否显示左侧icon
				type: [Boolean, String],
				default: false
			},
			mode: {
				//通告栏模式，可选值为 closeable link
				type: String,
				default: ''
			}
		},
		data() {
			const elId = `Hbie_${Math.ceil(Math.random() * 10e5).toString(36)}`
			const elIdBox = `Hbie_${Math.ceil(Math.random() * 10e5).toString(36)}`
			return {
				textWidth: 0,
				boxWidth: 0,
				wrapWidth: '',
				webviewHide: false,
				// #ifdef APP-NVUE
				stopAnimation: false,
				// #endif
				elId: elId,
				elIdBox: elIdBox,
				show: true,
				animationDuration: 'none',
				animationPlayState: 'paused',
				animationDelay: '0s'
			}
		},
		mounted() {
			// #ifdef APP-NVUE
			let pages = getCurrentPages();
			let page = pages[pages.length - 1];
			let currentWebView = page.$getAppWebview();
			currentWebView.addEventListener('hide', () => {
				this.webviewHide = true
			})
			currentWebView.addEventListener('show', () => {
				this.webviewHide = false
			})
			// #endif
			this.$nextTick(function() {
				this.init();
			})
		},
		// #ifdef APP-NVUE
		beforeDestroy() {
			this.stopAnimation = true
		}
		// #endif
		methods: {
			init() {
				if (this.scrollable) {
					// #ifndef APP-NVUE
					let query = [],
						boxWidth = 0,
						textWidth = 0;
					let textQuery = new Promise((resolve, reject) => {
						uni.createSelectorQuery()
							// #ifndef MP-ALIPAY
							.in(this)
							// #endif
							.select(`#${this.elId}`)
							.boundingClientRect()
							.exec(ret => {
								this.textWidth = ret[0].width;
								resolve();
							})
					})
					let boxQuery = new Promise((resolve, reject) => {
						uni.createSelectorQuery()
							// #ifndef MP-ALIPAY
							.in(this)
							// #endif
							.select(`#${this.elIdBox}`)
							.boundingClientRect()
							.exec(ret => {
								this.boxWidth = ret[0].width;
								resolve()
							})
					})
					query.push(textQuery);
					query.push(boxQuery);
					Promise.all(query).then(() => {
						this.animationDuration = `${this.textWidth / this.speed}s`
						this.animationDelay = `-${this.boxWidth / this.speed}s`
						setTimeout(() => {
							this.animationPlayState = 'running'
						}, 1000)
					})
					// #endif
					// #ifdef APP-NVUE
					dom.getComponentRect(this.$refs['animationEle'], (res) => {
						let winWidth = uni.getSystemInfoSync().windowWidth
						this.textWidth = res.size.width
						animation.transition(this.$refs['animationEle'], {
							styles: {
								transform: `translateX(-${winWidth}px)`
							},
							duration: 0,
							timingFunction: 'linear',
							delay: 0
						}, () => {
							if (!this.stopAnimation) {
								animation.transition(this.$refs['animationEle'], {
									styles: {
										transform: `translateX(-${this.textWidth}px)`
									},
									timingFunction: 'linear',
									duration: (this.textWidth - winWidth) / this.speed * 1000,
									delay: 1000
								}, () => {
									if (!this.stopAnimation) {
										this.loopAnimation()
									}
								});
							}
						});
					})
					// #endif
				}
				// #ifdef APP-NVUE
				if (!this.scrollable && (this.single || this.moreText)) {
					dom.getComponentRect(this.$refs['textBox'], (res) => {
						this.wrapWidth = res.size.width
					})
				}
				// #endif
			},
			loopAnimation() {
				// #ifdef APP-NVUE
				animation.transaction(this.$refs['animationEle'], {
					style: {
						transform: `translateX(0px)`
					},
					duration: 0
				}, () => {
					if (this.stopAnimation) {
						animation.transaction(this.$refs['animationEle'], {
							style: {
								transform: `translateX(-${this.textWidth}px)`
							},
							duration: this.textWidth / this.speed * 1000,
							timingFunction: 'linear',
							delay: 0
						}, () => {
							if (!this.stopAnimation) {
								this.loopAnimation()
							}
						});
					}
				});
				// #endif
			},
			clickMore() {
				this.$emit('getmore')
			},
			close() {
				this.show = false;
				this.$emit('close')
			},
			onClick() {
				this.$emit('click')
			}
		}
	}
</script>

<style lang="less">
	.hb-notice-bar {
		position: relative;
		display: flex;
		align-items: center;
		height: 80rpx;
		padding: 0 32rpx;
		font-size: 28rpx;
		color: #ed6a0c;
		background-color: #fffbe8;

		&--withicon {
			position: relative;
			padding-right: 80rpx;
		}

		&--wrapable {
			height: auto;
			padding: 16rpx 32rpx;

			.hb-notice-bar {
				&__wrap {
					height: auto;
				}

				&__content {
					position: relative;
					white-space: normal;
				}
			}
		}

		&__left-icon {
			display: flex;
			align-items: center;
			margin-right: 8rpx;
			vertical-align: middle;
			font-size: 32rpx;
			min-width: 44rpx;
		}

		&__right-icon {
			text-align: right;
			cursor: pointer;
			font-size: 32rpx;
			min-width: 44rpx;
		}

		&__wrap {
			position: relative;
			flex: 1;
			overflow: hidden;
			height: 48rpx;
			line-height: 48rpx;
		}

		&__content {
			position: absolute;
			white-space: nowrap;

			&.hb-ellipsis {
				max-width: 100%;
			}
		}

		&-text--scrollable {
			/* #ifdef APP-NVUE */
			lines: 1;
			padding-left: 750rpx;
			/* #endif */
			/* #ifndef APP-NVUE */
			position: absolute;
			display: block;
			height: 48rpx;
			line-height: 48rpx;
			white-space: nowrap;
			padding-left: 100%;
			animation: hb-notice-bar__play--infinite 10s 0s linear infinite both;
			animation-play-state: paused;
			/* #endif */
		}
	}

	@keyframes hb-notice-bar__play--infinite {
		100% {
			transform: translate3d(-100%, 0, 0);
		}
	}
</style>
